package cfca.seal.util;

import cfca.sadk.algorithm.common.PKIException;
import cfca.sadk.x509.certificate.X509CRL;
import cfca.sadk.x509.certificate.X509Cert;
import cfca.sadk.x509.certificate.X509CertVerifier;
import java.util.Date;
import java.util.List;

public class VerifyUtil
{
  public static boolean verifyCertDate(X509Cert signCert, Date checkTime)
  {
    return (signCert.getNotAfter().after(checkTime)) && (signCert.getNotBefore().before(checkTime));
  }

  public static boolean verifyCertDate(X509Cert signCert) {
    return X509CertVerifier.verifyCertDate(signCert);
  }

  public static boolean verifyCertDate(List<X509Cert> x509Certs) {
    boolean verify = true;
    for (X509Cert x509Cert : x509Certs) {
      if (!X509CertVerifier.verifyCertDate(x509Cert)) {
        verify = false;
        break;
      }
    }
    return verify;
  }

  public static boolean verifyCertDate(List<X509Cert> x509Certs, Date checkTime) {
    boolean verify = true;
    for (X509Cert x509Cert : x509Certs) {
      if ((x509Cert.getNotAfter().before(checkTime)) || (x509Cert.getNotBefore().after(checkTime))) {
        verify = false;
        break;
      }
    }
    return verify;
  }

  public static boolean verifyCertSign(X509Cert x509Cert, X509Cert trustCert) {
    boolean verify = false;
    try {
      X509CertVerifier.clearTrustCertsMap();
      X509CertVerifier.updateTrustCertsMap(trustCert);
      verify = X509CertVerifier.validateCertSign(x509Cert);
    } catch (PKIException e) {
      e.printStackTrace();
    }
    return verify;
  }

  public static boolean verifyCertSign(List<X509Cert> x509Certs, List<X509Cert> trustCerts) {
    boolean verify = true;
    X509Cert[] trusCertsArray = new X509Cert[trustCerts.size()];
    trustCerts.toArray(trusCertsArray);
    try {
      X509CertVerifier.clearTrustCertsMap();
      X509CertVerifier.updateTrustCertsMap(trusCertsArray);
      for (X509Cert x509Cert : x509Certs) {
        verify = (verify) && (X509CertVerifier.validateCertSign(x509Cert));
        if (!verify)
          break;
      }
    }
    catch (PKIException e) {
      verify = false;
    }
    return verify;
  }

  public static boolean verifyByCRL(X509Cert userCert, X509CRL x509crl) {
    String cert_sNum = userCert.getStringSerialNumber();
    return x509crl.isRevoke(cert_sNum);
  }
}